﻿using Practice_DotNet.Helper;
using Practice_DotNet.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice_DotNet.Operation
{
    internal class UserScoresOperation
    {
        public static async Task<List<UserScoresModel>?> GetAllScoreByUserAcount(string account)
        {
            List<UserScoresModel> userScoresModels = new List<UserScoresModel>();
            string commandStr = $"SELECT * FROM userscores where Account = '{account}' ";
            var result = await SQLHelper.SQL_CRUDOnlyRead(commandStr);
            if (result.Rows.Count > 0)
            {
                for (int i = 0; i < result.Rows.Count; i++)
                {
                    userScoresModels.Add(DataRowToUserScores(result.Rows[i]));
                }
            }
            else return null;
            return userScoresModels;
        }
        public static async Task<UserScoresModel?> GetUserLastScore(string account)
        {
            string sqlStr = $"""
                Select  * 
                from userscores 
                where Account='{account}' 
                order by Recorddate asc
                LIMIT 1;
                """;
            var result =await SQLHelper.SQL_CRUDOnlyRead(sqlStr);
            if (result.Rows.Count==0)
            {
                return null;
            }
            return DataRowToUserScores(result.Rows[0]);
        }


        private static UserScoresModel DataRowToUserScores(DataRow dataRow)
        {
            UserScoresModel userScoresModel = new UserScoresModel();
            userScoresModel.Account = dataRow["Account"].ToString() ?? "";
            userScoresModel.Chinese = Convert.ToSingle(dataRow["Chinese"]);
            userScoresModel.English = Convert.ToSingle(dataRow["English"]);
            userScoresModel.Math = Convert.ToSingle(dataRow["Math"]);
            userScoresModel.RecordDate = Convert.ToDateTime(dataRow["RecordDate"]);
            return userScoresModel;
        }


    }
}
